import java.util.Arrays;

public class MergeSortedArrays {
    public static void main(String[] args) {
        int[] num1 = new int[]{1, 2, 4, 6, 7, 123, 411, 5334, 1414141, 1314141414};
        int[] num2 = new int[]{0, 2, 57, 89, 113, 5623, 6353, 134134};

        int[] mergedArray = mergeArrays(num1, num2);

        System.out.println("数组1: " + Arrays.toString(num1));
        System.out.println("数组2: " + Arrays.toString(num2));
        System.out.println("合并后的有序数组: " + Arrays.toString(mergedArray));
    }

    public static int[] mergeArrays(int[] arr1, int[] arr2) {
        // 创建结果数组
        int[] result = new int[arr1.length + arr2.length];

        // 三个指针：i用于arr1，j用于arr2，k用于result
        int i = 0, j = 0, k = 0;

        // 比较两个数组的元素，将较小的放入结果数组
        while (i < arr1.length && j < arr2.length) {
            if (arr1[i] <= arr2[j]) {
                result[k] = arr1[i];
                i++;  // arr1的指针加一
            } else {
                result[k] = arr2[j];
                j++;  // arr2的指针加一
            }
            k++;  // 结果数组的指针加一
        }

        // 将剩余的元素复制到结果数组
        while (i < arr1.length) {
            result[k] = arr1[i];
            i++;
            k++;
        }

        while (j < arr2.length) {
            result[k] = arr2[j];
            j++;
            k++;
        }

        return result;
    }
}